package com.XSQS.storage.index;

import java.util.Arrays;

import org.apache.log4j.Logger;

import com.XSQS.util.Utility;

public class InvertedSearcher {

	private Logger logger = Utility.getLogger(InvertedSearcher.class);

	private static InvertedSearcher instance;

	private InvertedReader reader;

	private InvertedSearcher() {
		reader = InvertedReader.getInstance();
	}

	public synchronized static InvertedSearcher getInstance() {
		if (instance == null) {
			instance = new InvertedSearcher();
		}
		return instance;
	}

	public IndexEntry[] search(String key) {
		InvertedWordItem keyItem = new InvertedWordItem();
		keyItem.setKey(key);
		reader.open();
		InvertedWordItem[] items = reader.readAllInvertedWordItem();
		int hit = Arrays.binarySearch(items, keyItem);
		if (hit >= 0) {
			IndexEntry[] results = reader.readIndexEntries(items[hit]
					.getFirstEntry());
			reader.close();
			return results;
		} else {
			if (logger.isInfoEnabled()) {
				logger.info("Can not search the IndexEntry[] for the key: "+key);
			}
			reader.close();
			return null;
		}
	}

	public IndexEntry[] searchForMultiKeys(String keys) {
		String[] keyArray = keys.split("\\W+");
		IndexEntry[] result = search(keyArray[0]);
		for (int i = 1; i < keyArray.length; ++i) {
			IndexEntry[] tmp = search(keyArray[i]);
			result = Utility.getIntersection(result, tmp);
		}
		return result;
	}
	
}
